package summerprojectFX.view;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import summerprojectFX.model.Song;
import summerprojectFX.utilities.Transposer;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.effect.InnerShadow;
import javafx.scene.effect.InnerShadowBuilder;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;
import javax.swing.JScrollBar;
import summerprojectFX.controller.Checked;
import summerprojectFX.utilities.NashvilleNumbers;

public class MainView extends Application {

	private ListView<String> titleListView;
	private Text currentSong;
	private ArrayList<Song> allOpenSongs;
	private ObservableList<String> songTitles;
	private ComboBox NoteBox, KeyBox, stepsBox, directionBox, NoteBox1;
	private ScrollPane sp;
        private Checked checkOpen, checkFull;
        private Runnable waitRunner;
        private VBox attempt;
      

	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
                //SplashScreen ss = new SplashScreen();
		primaryStage.setTitle("Transposer Pro");
                
		// Gets Monitors resolution for the JFrame
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		final Dimension scrnsize = toolkit.getScreenSize();
                checkOpen = new Checked();
                checkFull = new Checked();
		Group root = new Group();
		Scene scene = new Scene(root, scrnsize.width / 1.16,
				scrnsize.height/1.16 , Color.LIGHTSTEELBLUE);
		allOpenSongs = new ArrayList<Song>();
                
                                    
		GridPane gridpane = new GridPane();
		gridpane.setPadding(new Insets(5));
		gridpane.setHgap(10);
		gridpane.setVgap(10);
                
                            

		final HBox hb2 = new HBox();
		hb2.setSpacing(30);
		hb2.setAlignment(Pos.CENTER_LEFT);

		final HBox hb1 = new HBox();
		hb1.setSpacing(20);
		hb1.setAlignment(Pos.TOP_RIGHT);

		final VBox Vb2 = new VBox();
		Vb2.setSpacing(20);
		Vb2.setAlignment(Pos.CENTER_LEFT);
		
		final HBox hb3 = new HBox();
		hb3.setSpacing(20);
		hb3.setAlignment(Pos.TOP_LEFT);
		
		final HBox hb4 = new HBox();
		hb4.setSpacing(20);
		hb4.setAlignment(Pos.TOP_LEFT);
		
		final HBox hb5 = new HBox();
		hb5.setSpacing(20);
		hb5.setAlignment(Pos.TOP_LEFT);
		
		final VBox vb3 = new VBox();
		vb3.setSpacing(20);
		vb3.setAlignment(Pos.TOP_LEFT);
		
		InnerShadow iShadow = InnerShadowBuilder.create().offsetX(1.5f)
				.offsetY(1.5f).build();
		Text songsOpenLbl = TextBuilder.create().effect(iShadow)
				.fill(Color.DARKGREY)
				.font(Font.font(null, FontWeight.BOLD, 25)).build();
		songsOpenLbl.setText("Songs");

		InnerShadow iShadow1 = InnerShadowBuilder.create().offsetX(1.5f)
				.offsetY(1.5f).build();

		Text keyLbl = TextBuilder.create().effect(iShadow1)
				.fill(Color.DARKGREY)
				.font(Font.font(null, FontWeight.BOLD, 15)).build();
		keyLbl.setText("Set Key");

		Text transLbl = TextBuilder.create().effect(iShadow1)
				.fill(Color.DARKGREY)
				.font(Font.font(null, FontWeight.BOLD, 15)).build();
		transLbl.setText("Transpose by Distance");

		Text transLbl2 = TextBuilder.create().effect(iShadow1)
				.fill(Color.DARKGREY)
				.font(Font.font(null, FontWeight.BOLD, 15)).build();
		transLbl2.setText("Transpose to New Key");

		currentSong = TextBuilder.create()
				.fill(Color.BLACK)
				.font(Font.font("monospace", FontWeight.BOLD, 15)).build();
               
		sp = new ScrollPane();
		sp.setContent(currentSong);
		sp.setPrefHeight(scrnsize.getHeight() / 1.9);
		sp.setPrefWidth(scrnsize.getWidth() / 3);
                 
                
		
		currentSong.setWrappingWidth(650);
               
		NoteBox = new ComboBox(FXCollections.observableArrayList(
				"Ab", "A", "A#", "Bb", "B", "C", "C#", "Db", "D", "D#", "Eb",
				"E", "F", "F#", "Gb", "G", "G#"));
		NoteBox.setValue("C");

		KeyBox = new ComboBox(FXCollections.observableArrayList(
				"Major", "Minor"));
		KeyBox.setValue("Major");

		stepsBox = new ComboBox(FXCollections.observableArrayList("0.5",
				"1", "1.5 ", "2", "2.5", "3", "3.5", "4", "4.5", "5", "5.5"));
		stepsBox.setValue("0.5");

		directionBox = new ComboBox(FXCollections.observableArrayList(
				"Up", "Down"));
		directionBox.setValue("Down");

		NoteBox1 = new ComboBox(FXCollections.observableArrayList(
				"Ab", "A", "A#", "Bb", "B", "C", "C#", "Db", "D", "D#", "Eb",
				"E", "F", "F#", "Gb", "G", "G#"));
		NoteBox1.setValue("C");

		NoteBox1.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
					NoteBox1.setValue(NoteBox1.getSelectionModel().getSelectedItem());
				}
			}
		});
		NoteBox.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
					NoteBox.setValue(NoteBox.getSelectionModel().getSelectedItem());
				}
			}
		});
		directionBox.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
					directionBox.setValue(directionBox.getSelectionModel().getSelectedItem());
				}
			}
		});
		stepsBox.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
					stepsBox.setValue(stepsBox.getSelectionModel().getSelectedItem());
				}
			}
		});
		KeyBox.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
					KeyBox.setValue(KeyBox.getSelectionModel().getSelectedItem());
				}
			}
		});
		

		final Button button = new Button("OK");
		button.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
                                    if(getSelectedSong().getTitle() != null)
					transposeByDistance();
				}
			}
		});

		final Button button2 = new Button("OK");
		button2.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
                                     if(getSelectedSong().getTitle() != null)
					transposeToKey();
				}
			}
		});
                final Button button3 = new Button("Number System");
		button3.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(final ActionEvent event) {
				{
                                    Song song = getSelectedSong();
                                    if(getSelectedSong().getTitle() != null){
					NashvilleNumbers nn = new NashvilleNumbers(currentSong.getText(),
						getKey());
                                        String numbersSong = nn.convert();
                                        
                                        song.setLyrics(numbersSong);
                                        song.setNumeric(numbersSong);
                                        currentSong.setText(song.getLyrics());
                                    }
				}
			}
		});

		
		songTitles = FXCollections.observableArrayList();
          

		titleListView = new ListView<String>(songTitles);
		titleListView.setPrefWidth(scrnsize.getWidth() / 7);
		titleListView.setPrefHeight(scrnsize.getHeight() / 1.8);
		//hb3.setStyle(" -fx-fill: yellow;-fx-stroke: green;-fx-stroke-width: 5;-fx-stroke-dash-array: 12 2 4 2;-fx-stroke-dash-offset: 6;-fx-stroke-line-cap: butt;");
                attempt = new VBox();
                
                
              
        Text temp = TextBuilder.create().font(Font.font(null, FontWeight.BOLD, 10)).build();
        Text temp2 = TextBuilder.create().font(Font.font(null, FontWeight.BOLD, 10)).build();
         Text temp3 = TextBuilder.create().font(Font.font(null, FontWeight.BOLD, 10)).build();
         Text transLbl3 = TextBuilder.create().effect(iShadow1)
				.fill(Color.DARKGREY)
				.font(Font.font(null, FontWeight.BOLD, 15)).build();
		transLbl3.setText("Change to Number System");
		hb3.getChildren().addAll(NoteBox, KeyBox);
		hb4.getChildren().addAll(stepsBox, directionBox, button);
		hb5.getChildren().addAll(NoteBox1, button2);
                attempt.getChildren().addAll(keyLbl, hb3, temp);
		vb3.getChildren().addAll(attempt, transLbl2, hb5, temp2, transLbl, hb4, temp3, transLbl3,  button3 );
		
		hb2.getChildren().addAll(titleListView, sp, vb3);

		Vb2.getChildren().addAll(songsOpenLbl, hb2);
		gridpane.add(Vb2, 2, 5);
		sp.setStyle("-fx-padding: 5 0 0 10;");
		MainMenu menu = new MainMenu();
		root.getChildren().add(gridpane);
		root.getChildren().add(menu.createMenu(primaryStage, this));
		titleListView.setOnMouseClicked(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent event) {
				String title = titleListView.getSelectionModel()
						.getSelectedItem();

				for (Song s : allOpenSongs) {
					if (s.getTitle().equals(title)) {
						currentSong.setText(s.getLyrics());
						break;
					}
				}
			}
		});

		scene.widthProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(
					ObservableValue<? extends Number> observableValue,
					Number oldSceneWidth, Number newSceneWidth) {
				sp.setPrefWidth(newSceneWidth.doubleValue() / 2);

			}
		});

		scene.heightProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(
					ObservableValue<? extends Number> observableValue,
					Number oldSceneHeight, Number newSceneHeight) {
				sp.setPrefHeight(newSceneHeight.doubleValue() / 1.2);
				

			}
		});

		primaryStage.setScene(scene);
		primaryStage.show();
                
               waitRunner = new Runnable()
            {
                public void run()
                {
                    try
                        {
                            Thread.sleep(2000);
                            
                        }
                    catch(Exception e)
                        {
                            e.printStackTrace();
                            // can catch InvocationTargetException
                            // can catch InterruptedException
                        }
                }
            };
          
                
                

	}

	public void addSong(Song song) {
		int i = 0;
		for (Song s : allOpenSongs) {
                        try{
                            String temp = s.getTitle().substring(0, song.getTitle().length());
                        
			if (song.getTitle().equals(temp)) {
				i++;
			}}catch(Exception e){
                            
                        }
                        
		}
		if (i != 0) {
			song.setTitle(song.getTitle() + "( " + i + " )");
		}

		allOpenSongs.add(song);
		songTitles.add(song.getTitle());
		
		currentSong.setText(song.getLyrics());
                System.out.println(song.getLyrics());
		titleListView.getSelectionModel().select(allOpenSongs.size() - 1);
		titleListView.getFocusModel().focus(allOpenSongs.size() - 1);
		titleListView.scrollTo(allOpenSongs.size() - 1);
             
                
          
		
	}

	public void clearList() {

		songTitles.clear();
		allOpenSongs.clear();
		currentSong.setText("");
	}

	public void clearSelected() {
		String temp = titleListView.getSelectionModel().getSelectedItem();
		if (temp != null) {
			songTitles.remove(temp);
			int i = 0;
			for (Song s : allOpenSongs) {
				if (s.getTitle().equals(temp)) {
					allOpenSongs.remove(i);
					break;
				}
				i++;
			}
			if (allOpenSongs.isEmpty()) {
				currentSong.setText("");
			}

		}
	}

	public Song getSelectedSong() {
		String title = titleListView.getSelectionModel().getSelectedItem();
		for (Song s : allOpenSongs) {
			if (s.getTitle().equals(title)) {
				return s;
			}
		}
		return new Song();
	}

	public void goToNumber(Song song) {
		currentSong.setText(song.getLyrics());
               
	}

	public void restore() {
          Song song = this.getSelectedSong();
          song.setPreviousKey((String)NoteBox.getValue());
		String temp = titleListView.getSelectionModel().getSelectedItem();
		if (temp != null) {
			for (Song s : allOpenSongs) {
				if (s.getTitle().equals(temp)) {
					s.setLyrics(s.getOriginalLyrics());
					currentSong.setText(s.getOriginalLyrics());
                                        NoteBox.setValue(s.getOriginalKey());
                                        NoteBox.setValue(s.getOriginalKey());
					break;
				}
			}
		}
	}

	public void previous() {
		{
			String temp = titleListView.getSelectionModel().getSelectedItem();
			if (temp != null) {
				for (Song s : allOpenSongs) {
					if (s.getTitle().equals(temp)) {
						s.setLyrics(s.getPreviousLyrics());
						currentSong.setText(s.getLyrics());
                                                NoteBox.setValue(s.getPreviousKey());
                                                NoteBox.setValue(s.getPreviousKey());
						break;
					}
				}
			}
		}
	}

	public String getKeyLetter() {
		return (String) NoteBox.getValue();
	}

	public void transposeByDistance() {
		Song song = this.getSelectedSong();
		String currentSong = song.getLyrics();
		Transposer tranny = new Transposer(currentSong, this.getKeyLetter(),
				this.getHalfSteps());
		String transposedSong = tranny.transpose();
		song.setLyrics(transposedSong);
                song.setPreviousKey((String)NoteBox.getValue());                
		NoteBox.setValue(tranny.getEndKey());
                NoteBox.setValue(tranny.getEndKey());
                song.setCurrentKey(tranny.getEndKey());
		this.goToNumber(song);
	}

	public void transposeToKey() {
		Song song = this.getSelectedSong();
		String currentSong = song.getLyrics();
		Transposer tranny = new Transposer(currentSong,(String) NoteBox.getValue(),
				(String)NoteBox1.getValue());
		String transposedSong = tranny.transpose();
		song.setLyrics(transposedSong);
                song.setPreviousKey((String)NoteBox.getValue());
                NoteBox.setValue((String)NoteBox1.getValue());
                NoteBox.setValue((String)NoteBox1.getValue());
                song.setCurrentKey((String)NoteBox1.getValue());
		this.goToNumber(song);
	}

	public String getKey() {
		return (String) NoteBox.getValue() + " " + (String) KeyBox.getValue();

	}

	public int getHalfSteps() {
		
		String steps = (String) stepsBox.getValue();
		if (directionBox.getValue().equals("Up")) 
			return (int)(2 * Double.parseDouble(steps));

		 else 
			return 12 - (int)(2 * Double.parseDouble(steps));
	}

	public ArrayList<Song> getCurrentSongs() {
		return allOpenSongs;
	}
        public boolean getCheckedOpen(){
            return checkOpen.getCheck();
        }
        public void setCheckedOpen(boolean checked){
            checkOpen.setCheck(checked);
        }
        public boolean getCheckedFull(){
            return checkFull.getCheck();
        }
        public void setCheckedFull(boolean checked){
            checkFull.setCheck(checked);
        }

}
